package com.gege.homework10.service;

import com.gege.homework10.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 使用 Hikari 连接池，实现数据入库
 *
 * @author gechenpeng
 * @date 2021-04-21
 */
@Service
public class UserService {

    @Autowired
    private DataSource dataSource;

    public void addUserInBulk(List<User> users) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            String sql = "INSERT INTO user (id, nickname) VALUES (?, ?)";
            statement = connection.prepareStatement(sql);

            for (User user : users) {
                statement.setString(1, user.getId());
                statement.setString(2, user.getNickname());

                statement.addBatch();
            }

            statement.executeBatch();

            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (null != statement) {
                    statement.close();
                }

                if (null != connection) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
